import requests
import psutil
import subprocess

def Checkout_Has_Msedge_Process(_process_name:str="msedge.exe"):
    """检查是否存在指定名称的进程
        
        Args:
            _process_name (str): 进程名称
        
        Returns:
            bool: 如果存在指定名称的进程，则返回 True，否则返回 False
        
        Example:
            >>> CheckMsEdgeProcess('msedge.exe')
            True
        """
    _is_process_running = False
    for _proc in psutil.process_iter(['name']):
        if _proc.info['name'] == _process_name:
            _is_process_running = True
            break
    return _is_process_running


def Checkout_Debug_Mode_Activate(url="http://127.0.0.1:9652/json/version") -> bool:
    """
    检查调试模式路径是否可用

    Returns:
        bool: 如果调试模式路径可用，则返回 True,否则返回 False

    Example:
        >>> MyEdge.CheckOutDebugModePath()
        True
    """
    try:
        response = requests.get(url=url)
        if response.status_code == 200:
            result = True
        else:
            result = False
    except Exception as e:
        print(f"请求调试模式路径时发生错误: {e}")
        result = False
    return result


def Close_All_Msedge_Process(_process_name: str="msedge.exe") -> bool:
    """
    关闭所有指定名称的进程

    Args:
        _process_name (str): 进程名称

    Returns:
        bool: 如果成功关闭所有指定名称的进程，则返回 True，否则返回 False

    Example:
        >>> MyEdge.CloseAllMsEdgeProcess('msedge.exe')
        True
    """
    success = True  # 初始化返回值
    for proc in psutil.process_iter(['pid', 'name']):
        if _process_name == proc.info['name']:
            try:
                proc.kill()  # 关闭进程
                print(f"Closed Microsoft Edge process with PID: {proc.info['pid']}")
            except Exception as e:
                print(f"Failed to close Microsoft Edge process with PID: {proc.info['pid']}. Error: {e}")
                success = False  # 如果关闭失败，设置返回值为 False
    return success

def Start_Debugmode_Browser():
    # 定义启动命令
    command = r'"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" \
            --remote-debugging-port=9652 \
            --disable-extensions \
            "http://127.0.0.1:9652/json/version" \
            "https://fxg.jinritemai.com/ffa/mshop/homepage/index" \
            "https://myseller.taobao.com/home.htm/QnworkbenchHome/"'
    
    # 启动新的进程
    subprocess.Popen(command, shell=True)

def Start_Debugmode_Browser_With_Extensions():
    # 定义启动命令
    command = r'"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" \
            --remote-debugging-port=9652 \
            "http://127.0.0.1:9652/json/version" '
            
    
    # 启动新的进程
    subprocess.Popen(command, shell=True)
